/**
 * 存放页面上关于绘图的函数
 */

/**
 * 玫瑰图外环
 * @param {Array} arrRadius 半径
 * @param {Array} arrCenter 圆心
 */
var waiyuan=function(arrRadius,arrCenter){
	return {
		type:'pie'
	    ,tooltip : {
	    	show:false
	    	,showContent:false
	    }
	    ,z:-1
	    ,color:['#ddd']
	    ,radius : arrRadius
	    ,center : arrCenter
	    ,legendHoverLink:false
	    ,selectedMode:false
	    ,selectedOffset:0
	    ,label: {
	        normal: {
	            show: false
	        }
	    },
	    labelLine:{
	    	normal: {
	            show: false
	        }
	    },
	    data:[
	        {}
	    ]
	}
}

/**
 * //玫瑰图内环
 * @param {Array} arrRadius 半径
 * @param {Array} arrCenter 圆心
 */
var neiyuan=function(arrRadius,arrCenter){
	return {
		type:'pie'
	    ,tooltip : {
	    	show:false
	    	,showContent:false
	    }
	    ,z:-1
	    ,color:['#ddd']
	    ,radius : arrRadius
	    ,center : arrCenter
	    ,legendHoverLink:false
	    ,selectedMode:false
	    ,selectedOffset:0
	    ,label: {
	        normal: {
	            show: false
	        }
	    },
	    labelLine:{
	    	normal: {
	            show: false
	        }
	    },
	    data:[
	        {}
	    ]
	}
}


/**
 * //ajax获取接口数据
 * @param {String} url 接口地址
 * @param {Function} callback 回调函数
 */
function get_wrchat_data(url,callback){
	$.ajax({
      	type: "get"
      	,cache:true
      	,contentType: "application/json; charset=utf-8"
      	,dataType: "json"
      	,url: url//+'&callback=?'
      	,timeout: 60000
      	,success: function (json) {
      		if(json.Error==null){
				callback(json);
			}else{
				console.log(json.Error);
			}
      	}
      	,error: function (XMLHttpRequest, textStatus, errorThrown) {
          	console.error(url,textStatus+": "+errorThrown);
      	}
  	});
}

/**
 * //根据数组按区间分段
 * @param {Array} data 原始数据
 * @param {Array} sort 排序依据 example:[20,60,90]
 * @param {Boolean} fromhead 是否从零开始，默认为是
 */
function dataSort(data,sort,fromhead){
	fromhead = fromhead == false ? false : true;
	var l=sort.length;//4
	if(fromhead){
		l++;//5
	}
	
	var returnobj=[];
//	returnobj[l-1]=[];//arr[3]
//	console.log(fromhead,sort,data);
	for(var j=0;j<l;j++){//20,60,90
		returnobj[j]=[];//arr[0] arr[1] arr[2] arr[3]
		$.each(data,function(i,e){
			e=parseInt(e);
			if(fromhead){
				if(e<=sort[j]&&j==0){
					returnobj[j].push(e);
				}else if(j>0&&e<=sort[j]&&e>sort[j-1]&&j<(l-1)){
					returnobj[j].push(e);
				}
				if(j==(l-1)&&e>sort[j-1]){
					returnobj[j].push(e);
				}
			}else{
				if(e>=sort[j]&&j==0&&e<=sort[j+1]){//j=0
					returnobj[j].push(e);
				}else if(j>0&&e<=sort[j+1]&&e>sort[j]&&j<(l-1)){//j>0
					returnobj[j].push(e);
				}
				if(j==(l-1)&&e>sort[j]){
					returnobj[j].push(e);
				}
			}
		})
	}
//	console.log(returnobj);
	return returnobj;
}

/**
 * //根据指标name生成对应colors数组
 * @param {String} name 指标 example:so2
 * :TODO//可能需要添加大小写判断
 */
function wr_pie_getColors(name){
	// if(name=='so2'){
	// 	return ['#76d3ff','#32cd33','#f7d100','#eb6161'];
	// }
	// if(name=='no2'){
	// 	return ['#76d3ff','#32cd33','#f7d100','#eb6161'];
	// }
	// if(name=='pm10'){
	// 	return ['#76d3ff','#32cd33','#f7d100','#eb6161'];
	// }
	// if(name=='pm25'){
	// 	return ['#32cd33','#f7d100','#eb6161','#e240ca'];
	// }
	// if(name=='o3'){
	// 	return ['#76d3ff','#32cd33','#f7d100'];
	// }
	// if(name=='co'){
	// 	return ['#76d3ff','#32cd33','#f7d100'];
	// }
	return ['#22ad3a', '#eddd4c', '#ff9d02', '#f93702', '#ce162e', '#8e0c30', '#8e0c30', '#8e0c30', '#8e0c30', '#8e0c30']
}


/**
 * //生成series数组for echarts 玫瑰图
 * @param {Array} arr 原始数据
 * @param {Array} sort 排序依据
 * @param {String} nametitle 指标name
 * @param {Boolean} fromhead 是否从零开始 :REMARK//目前只有pm2.5不是从零开始的[15,35,70,100]分为4段
 */
function wr_pie_getSeries2(arr,sort,nametitle,fromhead){
	fromhead = fromhead == false ? false : true;
//	console.log(getDatatmp(arr,sort,fromhead));
	var t = getDatatmp2(arr,sort,fromhead);
	var sd = t[0];
	var ld = t[1];
	var series = [
        {
            type:'pie'
            ,radius : ['20%', '50%']
            ,center : ['50%', '50%']
            ,roseType : 'radius'
            ,colors:wr_pie_getColors(nametitle)
            ,legendHoverLink:false
            ,selectedMode:false
            ,selectedOffset:0
            ,label: {
                normal: {
                    show: true
                    ,position:'outside'
                    ,formatter:'{d}%'
                    ,textStyle:{
                    	color:'#000'
                    	,fontSize:8
                    }
                }
            }
            ,data:sd
        }
        ,waiyuan(['55%', '56%'],['50%', '50%'])
        ,neiyuan(['16%', '17%'],['50%', '50%'])
    ];
	return [series,ld];
}

/**
 * 根据数据跟区间重新排列
 * @param {Array} arr
 * @param {Array} sort 用来排序的区间数组
 * @param {Boolean} fromhead 是否从0开始
 */
var getDatatmp = function(arr,sort,fromhead){
	fromhead = fromhead == false ? false : true;
	var l=arr.length;//4
	var arrtmp=[],e,f;
//	console.log(fromhead,sort,arr);
	$.each(arr,function(i,ele){
//		console.log(arr[i].length);
		if(i==0){
			e=sort[i];
			f=sort[i+1];
			if(fromhead){
				if(arr[i].length<1){
					var tmp={name:'<='+e,y:0,dataLabels:{enabled:false}};
					arrtmp.push(tmp);
				}else{
					arrtmp.push(['<='+e,arr[i].length]);
				}
			}else{
				if(arr[i].length<1){
					var tmp={name:e+'~'+f,y:0,dataLabels:{enabled:false}};
					arrtmp.push(tmp);
				}else{
					arrtmp.push([e+'~'+f,arr[i].length]);
				}
			}
		}else if(i<(l-1)){
			if(fromhead){
				e=sort[i-1];
				f=sort[i];
			}else{
				e=sort[i];
				f=sort[i+1];
			}
			if(arr[i].length<1){
					var tmp={name:e+'~'+f,y:0,dataLabels:{enabled:false}};
					arrtmp.push(tmp);
				}else{
					arrtmp.push([e+'~'+f,arr[i].length]);
				}
			
		}
		if(i==(l-1)){//3
			if(fromhead){
				e=sort[i-1];
			}else{
				e=sort[i];
			}
			if(arr[i].length<1){
				var tmp={name:'>'+e,y:0,dataLabels:{enabled:false}};
				arrtmp.push(tmp);
			}else{
				arrtmp.push(['>'+e,arr[i].length]);
			}
		}
	})
	return arrtmp;
}

$.extend({
    Object:{
        count: function( p ) {
            p = p || false;
            return $.map( this, function(o) {
                if( !p ) return o;
                return true;
            } ).length;
        }
    }
});

/**
 * 根据数据跟区间重新排列//for echarts玫瑰图版本
 * @param {Array} arr
 * @param {Array} sort 用来排序的区间数组
 * @param {Boolean} fromhead 是否从0开始
 */
var getDatatmp2 = function(arr,sort,fromhead){
	fromhead = fromhead == false ? false : true;
	var l=$.Object.count.call(arr) - 2;//4
	var arrtmp=[],e,f,k;
	var arrLengend=[];
	$.each(arr,function(i,ele){
		if(i!=='date'&&i!=='name'){
			k = i.substr(1);
			if(k==1){
				e=sort[(k-1)];
				f=sort[k];
				if(fromhead){
					if(ele<1){
						var tmp={name:'<='+e,value:0,label :{normal :{show:false}},labelLine:{normal :{show:false}}};
						arrtmp.push(tmp);
						arrLengend.push('<='+e);
					}else{
						var tmp={name:'<='+e,value:ele};
						arrtmp.push(tmp);
						arrLengend.push('<='+e);
					}
				}
			}else if(k<l){
				if(fromhead){
					e=sort[k-2];
					f=sort[k-1];
				}else{
					e=sort[k-1];
					f=sort[k];
				}
				if(ele<1){
					var tmp={name:e+'~'+f,value:0,label :{normal :{show:false}},labelLine:{normal :{show:false}}};
					arrtmp.push(tmp);
					arrLengend.push(e+'~'+f);
				}else{
					var tmp={name:e+'~'+f,value:ele};
					arrtmp.push(tmp);
					arrLengend.push(e+'~'+f);
				}
			}
			
			if(k==(l-1)){//3
				if(fromhead){
					e=sort[k-1];
				}else{
					e=sort[k];
				}
				if(ele<1){
					var tmp={name:'>'+e,value:0,label :{normal :{show:false}},labelLine:{normal :{show:false}}};
					arrtmp.push(tmp);
					arrLengend.push('>'+e);
				}else{
					var tmp={name:'>'+e,value:ele};
					arrtmp.push(tmp);
					arrLengend.push('>'+e);
				}
			}
		}
//		if(i==0){
//			e=sort[i];
//			f=sort[i+1];
//			if(fromhead){
//				if(arr[i].length<1){
//					var tmp={name:'<='+e,value:0,label :{normal :{show:false}},labelLine:{normal :{show:false}}};
//					arrtmp.push(tmp);
//					arrLengend.push('<='+e);
//				}else{
//					var tmp={name:'<='+e,value:arr[i].length};
//					arrtmp.push(tmp);
//					arrLengend.push('<='+e);
//				}
//			}else{
//				if(arr[i].length<1){
//					var tmp={name:e+'~'+f,value:0,label :{normal :{show:false}},labelLine:{normal :{show:false}}};
//					arrtmp.push(tmp);
//					arrLengend.push(e+'~'+f);
//				}else{
//					var tmp={name:e+'~'+f,value:arr[i].length};
//					arrtmp.push(tmp);
//					arrLengend.push(e+'~'+f);
//				}
//			}
//		}else if(i<(l-1)){
//			if(fromhead){
//				e=sort[i-1];
//				f=sort[i];
//			}else{
//				e=sort[i];
//				f=sort[i+1];
//			}
//			if(arr[i].length<1){
//				var tmp={name:e+'~'+f,value:0,label :{normal :{show:false}},labelLine:{normal :{show:false}}};
//				arrtmp.push(tmp);
//				arrLengend.push(e+'~'+f);
//			}else{
//				var tmp={name:e+'~'+f,value:arr[i].length};
//				arrtmp.push(tmp);
//				arrLengend.push(e+'~'+f);
//			}
//		}
//
//		if(i==(l-1)){//3
//			if(fromhead){
//				e=sort[i-1];
//			}else{
//				e=sort[i];
//			}
//			if(arr[i].length<1){
//				var tmp={name:'>'+e,value:0,label :{normal :{show:false}},labelLine:{normal :{show:false}}};
//				arrtmp.push(tmp);
//				arrLengend.push('>'+e);
//			}else{
//				var tmp={name:'>'+e,value:arr[i].length};
//				arrtmp.push(tmp);
//				arrLengend.push('>'+e);
//			}
//		}

	})
//	console.log(arrtmp,arrLengend);
	return [arrtmp,arrLengend];
}

function set_wrchat_data_byyear(url,year){
	var hisdata;
	var indexof = DataCaches['aqiitemsyear']['year'].indexOf(year);
	if(indexof<0 || !DataCachesEnable){
		//get_wrchat_data(url+'/data?act=aqiitemsyear&areacode=2000&year='+year,function(obj){
		get_wrchat_data(url+'/data?act=maxaqiitemyear&areacode=2000&year='+year,function(obj){
		// get_wrchat_data('http://192.168.6.17:8585/data?act=aqiitemsday&areacode=2000&month='+month,function(obj){
			hisdata = obj.Data;
			DataCaches['aqiitemsyear']['year'].push(year);//加入缓存
			DataCaches['aqiitemsyear']['data'].push(hisdata);
			_aqiitemsday_dofun(hisdata,'wrchat-eveyearbili');
		});
	}else{
		hisdata = DataCaches['aqiitemsyear']['data'][indexof];
		_aqiitemsday_dofun(hisdata,'wrchat-eveyearbili');
	}
}
/**
 *
 * 每月污染物浓度比例图一
 * @param {String} url 请求地址
 * @param {String} month 月份
 */
function set_wrchat_data_bymonth(url,month){
	var hisdata;
	var indexof = DataCaches['aqiitemsday']['month'].indexOf(month);
	if(indexof<0 || !DataCachesEnable){
		//get_wrchat_data(url+'/data?act=aqiitemsday&areacode=2000&month='+month,function(obj){
		get_wrchat_data(url+'/data?act=maxaqiitemmonth&areacode=2000&month='+month,function(obj){
		// get_wrchat_data('http://192.168.6.17:8585/data?act=aqiitemsday&areacode=2000&month='+month,function(obj){
			hisdata = obj.Data;
			DataCaches['aqiitemsday']['month'].push(month);//加入缓存
			DataCaches['aqiitemsday']['data'].push(hisdata);
			_aqiitemsday_dofun(hisdata);
		});
	}else{
		hisdata = DataCaches['aqiitemsday']['data'][indexof];
		_aqiitemsday_dofun(hisdata);
	}
}
function _aqiitemsday_dofun(hisdata,id){
	var d=[];
	var id = id||'wrchat-evemonbili';
	var countZhibiao={
		no2:0,so2:0,pm10:0,pm25:0,o3:0,co:0
	};
	if(hisdata.length<1) return $('#'+id).html('');
	$.each(hisdata, function(i,e) {
		if(id=='wrchat-evemonbili'){
			if(e!==null){
				countZhibiao.pm25 = parseInt(e.pm25);
				countZhibiao.pm10 = parseInt(e.pm10);
				countZhibiao.so2 = parseInt(e.so2);
				countZhibiao.no2 = parseInt(e.no2);
				countZhibiao.co = parseInt(e.co);
				countZhibiao.o3 = parseInt(e.o3);
//				if(e.toUpperCase()=='NO2'){
//					countZhibiao.no2++;
//				}else if(e.toUpperCase()=='SO2'){
//					countZhibiao.so2++;
//				}else if(e.toUpperCase()=='PM10'){
//					countZhibiao.pm10++;
//				}else if(e.toUpperCase()=='PM2.5'||e.toUpperCase()=='PM25'){
//					countZhibiao.pm25++;
//				}else if(e.toUpperCase()=='O3'){
//					countZhibiao.o3++;
//				}else if(e.toUpperCase()=='CO'){
//					countZhibiao.co++;
//				}
			}
		}else{
			countZhibiao.pm25 = countZhibiao.pm25 + parseInt(e.pm25);
			countZhibiao.pm10 = countZhibiao.pm10 + parseInt(e.pm10);
			countZhibiao.so2 = countZhibiao.so2 + parseInt(e.so2);
			countZhibiao.no2 = countZhibiao.no2 + parseInt(e.no2);
			countZhibiao.co = countZhibiao.co + parseInt(e.co);
			countZhibiao.o3 = countZhibiao.o3 + parseInt(e.o3);
		}
	});
//		console.log(countZhibiao);
	var show1=countZhibiao.pm25==0?false:true
	,show2=countZhibiao.pm10==0?false:true
	,show3=countZhibiao.so2==0?false:true
	,show4=countZhibiao.no2==0?false:true
	,show5=countZhibiao.co==0?false:true
	,show6=countZhibiao.o3==0?false:true;
	d=[
	{name:'PM2.5',value:countZhibiao.pm25,label:{normal:{show:show1}},labelLine:{normal:{show:show1}}}
	,{name:'PM10',value:countZhibiao.pm10,label:{normal:{show:show2}},labelLine:{normal:{show:show2}}}
	,{name:'SO2',value:countZhibiao.so2,label:{normal:{show:show3}},labelLine:{normal:{show:show3}}}
	,{name:'NO2',value:countZhibiao.no2,label:{normal:{show:show4}},labelLine:{normal:{show:show4}}}
	,{name:'CO',value:countZhibiao.co,label:{normal:{show:show5}},labelLine:{normal:{show:show5}}}
	,{name:'O3',value:countZhibiao.o3,label:{normal:{show:show6}},labelLine:{normal:{show:show6}}}];

	var option = {
	    tooltip : {
	    	show:true
	    	,showContent:true
	    	,formatter:'{b}:{d}%'
	    }
	    ,legend: {
	    	show:false
//	    	,orient:'vertical'
//	    	,left:'right'
//	    	,top:'middle'
//	    	,width:'100%'
//	    	,data:['pm25','pm10','so2','no2','co','o3']
	    }
	    ,color:['#e240ca', '#eb6161', '#f7d100', '#32cd33', '#76d3ff', '#ff9d02']
	    ,series : [
	        {
	            type:'pie',
	            radius : ['20%', '50%'],
	            center : ['50%', '50%'],
	            roseType : 'radius'
	            ,legendHoverLink:false
	            ,selectedMode:false
	            ,selectedOffset:0
	            ,label: {
	                normal: {
	                    show: true
	                    ,position:'outside'
	                    ,formatter:'{b} : {c}天'
	                    ,textStyle:{
	                    	color:'#000'
	                    	,fontSize:8
	                    }
	                }
	            }
	            ,data:d
	        }
	        ,waiyuan(['55%', '56%'],['50%', '50%'])
	        ,neiyuan(['16%', '17%'],['50%', '50%'])
	    ]
	};
	var myChart = echarts.init(document.getElementById(id));
	myChart.setOption(option);
}

/**
 * 工业排放量条形图
 * 给数据分组作为条形图的series
 * @param {Object} arr
 */
function get_columngroup_series(arr,msdata){
//	var tmp=[],so2=[],yc=[],dy=[],fq=[],name1,name2,name3,name4;
	var tmp=[],so2=[],yc=[],dy=[],name1,name2,name3;
	$.each(arr, function(i,e) {
		$.each(e, function(j,f) {
			if(f.code==201){
				name1=f.name;
				so2.push(parseFloat(f.pfl ? f.pfl : 0));
			}
			if(f.code==203){
				name2=f.name;
				dy.push(parseFloat(f.pfl ? f.pfl : 0));
			}
			if(f.code==207){
				name3=f.name;
				yc.push(parseFloat(f.pfl ? f.pfl : 0));
			}
//			if(f.code==210){
//				name4=f.name;
//				fq.push(parseFloat(f.pfl ? f.pfl : 0));
//			}
		});
	});
	tmp.push({name:name1,stack:'so2',data:so2});
	tmp.push({name:name2,stack:'yc',data:yc});
	tmp.push({name:name3,stack:'dy',data:dy});
//	tmp.push({name:name4,stack:'fq',data:fq,visible:false});
	tmp.push({
				name:'AQI'
				,type:'spline'
				,color:'#e16f6e'
				,data:msdata
				,yAxis: 1
			});
	return tmp;
}

/**
 * //玫瑰图二指标切换动作
 * @param {String} url 请求接口地址
 * @param {String} id =dom id
 * @param {String} month 月份
 * @param {String} zhibiao 指标
 */
function refreshChrat(url,id,month,zhibiao){
	var hisdata;
	var indexof = DataCaches['aqiitems']['month'].indexOf(month);
	if(indexof<0 || !DataCachesEnable){
		//data?act=itemlvlmonth&areacode=2000&month=2016-05
		get_wrchat_data(url+'/data?act=itemlvlmonth&areacode=2000&month='+month,function(obj){
		//get_wrchat_data(url+'/data?act=aqiitems&areacode=2000&month='+month,function(obj){
			hisdata = obj.Data;
			DataCaches['aqiitems']['month'].push(month);//加入缓存
			DataCaches['aqiitems']['data'].push(hisdata);
			_aqiitems_dofun(hisdata,zhibiao,id);
		});
	}else{
		hisdata = DataCaches['aqiitems']['data'][indexof];
		_aqiitems_dofun(hisdata,zhibiao,id);
	}
}
function _aqiitems_dofun(hisdata,zhibiao,id){
	//[old]if(hisdata.so2.length<1&&hisdata.no2.length<1&&hisdata.pm10.length<1&&hisdata.pm25.length<1&&hisdata.co.length<1&&hisdata.o3.length<1) return $('#'+id).html('');
	//各指标排序区间
	var sortby = {
		// so2:[20,60,90]
		// ,no2:[20,40,60]
		// ,pm10:[40,70,100]
		// ,pm25:[15,35,70,100]
		// ,o3:[100,160]
		// ,co:[2,4]
		so2:[50,150,475,800,1600]//,2100,2620]
		,no2:[40,80,180,280,565]//,750,940]
		,pm10:[50,150,250,350,420]//,500,600]
		,pm25:[35,75,115,150,250]//,350,500]
		,o3:[100,160,215,265,800]
		,co:[2,4,14,24,36]//,48,60]
		,aqi:[50,100,150,200,300]
	};
	var title=zhibiao=='pm25'?'PM2.5':zhibiao;
	
	$.each(hisdata, function(i,e) {
		if((e.name.toUpperCase())==(title.toUpperCase())){
			if((e.l1+e.l2+e.l3+e.l4+e.l5+e.l6)<1) return $('#'+id).html('');
			var sort = sortby[zhibiao.toLowerCase()];
			// if(zhibiao=='pm25'){
			// 	var tmpdata = dataSort(e,sort,false);
			// 	var t = wr_pie_getSeries2(tmpdata,sort,i,false);
			// 	var ss = t[0];
			// 	var ld = t[1];
			// }else{
//				var tmpdata = dataSort(e,sort);
				var t = wr_pie_getSeries2(e,sort,e.name.toLowerCase());
				var ss = t[0];
				var ld = t[1];
			// }
			
			var option = {
				title:{
					show:true,
					text:title.toUpperCase()+''+getDW(title.toUpperCase()),
					top:'center',
					left:'center',
					textStyle:{
						fontSize:10
					}	
				},
			    tooltip : {
			    	show:true
			    	,showContent:true
			    	,formatter:'{b}: {c}天'
			    }
			    ,legend: {
			    	show:true
			    	,orient:'horizontal'//horizontal vertical
			    	,left:'center'
			    	,top:'top'
			    	,data:ld
			    	,itemGap:3
			    	,itemWidth:10
			    	,itemHeight:10
					,textStyle:{
						fontSize:10
					}
			    }
			    ,color:wr_pie_getColors()//getZhibiaoColorsByName(zhibiao)
			    ,series:ss
			};
			var myChart = echarts.init(document.getElementById(id));
			myChart.setOption(option);
		}
	});
}
function getDW(t){
	if(t=='AQI'){
		return '\n(指数)'
	}else if(t=='CO'){
		return '\n(mg/m³)'
	}else{
		return '\n(ug/m³)'
	}
}
function getZhibiaoColorsByName(name){
	// if(name=='aqi'){
		return ['#22ad3a', '#eddd4c', '#ff9d02', '#f93702', '#ce162e', '#8e0c30'];
	// }else{
		// return ['#76d3ff', '#32cd33','#f7d100',  '#ec6260', '#04e1da', '#e240ca'];
	// }
}

/**
 * 空气质量天数比例
 * 堆叠柱状图的绘制
 * 获取从当月开始往前12个月的所有数据然后刷新图表
 * @param {String} url
 * @param {String} id
 */
function make_wrchat_column(url,id){
	var hisdata;
	var indexof = DataCaches['aqidays'].length;
	if(indexof<1 || !DataCachesEnable){
//		get_wrchat_data(url+'/data?act=aqidays&areacode=2000',function(obj){
		get_wrchat_data(url+'/data?act=aqidays_new&areacode=2000',function(obj){
			hisdata = obj.Data;
			DataCaches['aqidays']=hisdata;//加入缓存
			_aqidays_dofun(hisdata,id);
		});
	}else{
		hisdata = DataCaches['aqidays'];
		_aqidays_dofun(hisdata,id);
	}
}
function _aqidays_dofun(hisdata,id){
	var ta = [];
	$.each(hisdata, function(i,e) {
		ta.push(e);
	});
	hisdata = ta.reverse();
	var colxAxis=[];
	var rt=[],ar1=0,ar2=0,ar3=0,ar4=0,ar5=0,ar6=0;
	var arr1=[0,0,0,0,0,0,0,0,0,0,0,0]
	,arr2=[0,0,0,0,0,0,0,0,0,0,0,0]
	,arr3=[0,0,0,0,0,0,0,0,0,0,0,0]
	,arr4=[0,0,0,0,0,0,0,0,0,0,0,0]
	,arr5=[0,0,0,0,0,0,0,0,0,0,0,0]
	,arr6=[0,0,0,0,0,0,0,0,0,0,0,0];
	var index=0;
	$.each(hisdata, function(i,e) {
		colxAxis.push(e.date);
		ar1=ar2=ar3=ar4=ar5=ar6=0;
		arr1[index]=e.l1;
		arr2[index]=e.l2;
		arr3[index]=e.l3;
		arr4[index]=e.l4;
		arr5[index]=e.l5;
		arr6[index]=e.l6;
//		$.each(e[1], function(j,f) {
//			var tmp = parseFloat(f);
//			if(tmp>=0 && tmp<=50){
//				ar1++;
//			}else if(tmp<=100){
//				ar2++;
//			}else if(tmp<=150){
//				ar3++;
//			}else if(tmp<=200){
//				ar4++;
//			}else if(tmp<=250){
//				ar5++;
//			}else if(tmp<=300){
//				ar6++;
//			}
//		})
//		arr1[index]=ar1;
//		arr2[index]=ar2;
//		arr3[index]=ar3;
//		arr4[index]=ar4;
//		arr5[index]=ar5;
//		arr6[index]=ar6;
		index++;
	});
	//每个arr代表一个分段的12个月天数数据
	var colseries=[{data:arr6},{data:arr5},{data:arr4},{data:arr3},{data:arr2},{data:arr1}];
	
	$('#'+id).highcharts({
         chart: {
            type: 'column'
        },
        title: {
            text: null
        },
        colors:['#8e0c30','#ce162e','#f93702','#ff9d02','#eddd4c','#22ad3a'],
        yAxis: {
            endOnTick:false,
            title: {
                text: null
            },
            tickWidth:1,
            lineWidth:1,
            minPadding:0.05,
            gridLineWidth:0,
            labels:{
            	format:'{value}%'
            }
        },
        credits:{
        	enabled: false
        },
        tooltip:{
        	formatter:function(){
        		return this.x+':('+this.y+'天)';
        	}
        },
        legend:{
        	enabled:false
        },
        plotOptions: {
            column: {
                stacking: 'percent',//normal percent
                pointPadding:0.05
                ,groupPadding:0
                ,borderWidth:0
            }
        },
        xAxis: {
            categories: colxAxis
            ,tickLength:0
            ,labels:{
            	step:1
            	,rotation:315
            }
        },
		series: colseries
    });
}

/**
 * 工厂排放量分组图
 * 获取数个月份的数据然后刷新图表
 * json数据中的date为日期，其他参数分别代表：so2:'二氧化硫日均排放量',yc:'烟尘排放总量',dy:'氮氧化物排放日均排放量',fq:'废气量'
 * @param {String} url
 * @param {String} id
 */
function make_wrchat_columngroup(url,id){
	var hisdata;
	var indexof = DataCaches['gypf'].length;
	if(indexof<1 || !DataCachesEnable){
		get_wrchat_data(url+'/data?act=gypf',function(obj){
			hisdata = obj.Data;
			DataCaches['gypf']=hisdata;//加入缓存
			_gypf_dofun(hisdata,id);
		});
	}else{
		hisdata = DataCaches['gypf'];
		_gypf_dofun(hisdata,id);
	}
}
function _gypf_dofun(hisdata,id){
	$.each(hisdata, function(i,e) {
		hisdata[i]=e.reverse();
	});
	var colxAxis=[];
	$.each(hisdata, function(i,e) {
		if(i==201){
			$.each(e, function(j,f) {
				colxAxis.push(f.date);
			});
		}
	});
	//获取aqims
	var indexofaqi = DataCaches['aqims'].length;
	var msdata=[];
	if(indexofaqi<1 || !DataCachesEnable){
		get_wrchat_data(RequestUrl+'/data?act=aqim_new&areacode=2000',function(obj){
			var tmpd = obj.Data.reverse();
			var tmpa = [];
			for(var i in tmpd){
				tmpa[tmpd[i].date] = tmpd[i].aqi;
			}
			DataCaches['aqims']=msdata=tmpa;//加入缓存
			_after_gypf_dofun(id,colxAxis,hisdata,msdata);
		});
	}else{
		msdata = DataCaches['aqims'];
		_after_gypf_dofun(id,colxAxis,hisdata,msdata);
	}
}
function _after_gypf_dofun(id,colxAxis,hisdata,msdata){
	var msa = [];
	for(var i in colxAxis){
		if(msdata[colxAxis[i]]){
			var v=parseFloat( msdata[colxAxis[i]].toFixed(1) );
			msa.push( {y:v,color:num2color(v)} );
		}else{
			msa.push( null );
		}
	}
	var now=new Date();
	var max= new Date(now.getFullYear(),now.getMonth(),0).getDate();
	var curday = new Date().getDate();
	var colseries = get_columngroup_series(hisdata,msa);
	colseries=colseries.map(function(e){
		// if(e.name!='AQI'){
		// 	var l=e.data.length-1;
		// 	console.log(e.data[l],max,curday);
		// 	e.data[l]=e.data[l]*max/curday;
		// }
		e.data.pop();
		return e
	});

	$('#'+id).highcharts({
         chart: {
         	type:'column',
         	zoomType: 'xy'
        },
        title: {
            text: null
        },
        tooltip:{
        	crosshairs:true,
        	shared:true
        },
        colors:['#21bb01','#ff9d02','#eddd4c'],//colors:['#21bb01','#ff9d02','#eddd4c','#f93702'],
        yAxis: [
        	{
	            endOnTick:false,
	            title: {
	                text: '吨'
					,align:'high'
					,offset: -15
					,rotation: 0
					,y:10
	            },
	            tickWidth:1,
	            tickLength:5,
	            lineWidth:1,
	            minPadding:0.05,
	            gridLineWidth:0
				,labels:{
					formatter:function(v){
						return this.value+'';
					}
					,useHTML:false
					,style:{
						'font-size':'10px'
					}
				}
	        }
        	,{
	            title: {
	                text: '指数'
					,align:'high'
					,offset: -25
					,rotation: 0
					,y:10
	            },
	            tickWidth:1,
	            tickLength:5,
	            lineWidth:1,
	            minPadding:0.05,
	            gridLineWidth:0,
            	opposite: true
				,min:0
				,labels:{
					formatter:function(v){
						return num2table(this.value).note+'<br/><br/>'+this.value;
					}
					,useHTML:true
					,style:{
						'font-size':'10px'
					}
					,y:-30
				}
	        }
        ],
        credits:{
        	enabled: false
        },
        legend: {                                                          
            align: 'center',
            verticalAlign: 'top',
            borderWidth: 0,
            backgroundColor: '#FFFFFF',
            shadow: false,
        	symbolHeight: 10,
        	symbolPadding:2,
        	symbolWidth:10,
        	margin: 2,
        	padding: 3,
        	itemStyle:{fontWeight: 'normal',fontSize:'0.6rem',lineHeight:'0.6rem'}
        	,itemDistance:5
        },
        plotOptions: {
            column: {
                stacking: 'normal',//percent
                pointPadding:0
                ,borderWidth:0
            }
        },
        xAxis: {
            categories: colxAxis
            ,tickLength:0
            ,labels:{
            	step:1
            	,rotation:315
            }
        },
		series:colseries
    });
}


function num2table(num){
		var num=parseInt(num);
		var idx=0,note='';
		if(num<50){
			idx=0;
			note='优秀';
		}else if(50<=num&&num<100){
			idx=1;
			note='良好';
		}else if(100<=num&&num<150){
			idx=2;
			note='轻度';
		}else if(150<=num&&num<200){
			idx=3;
			note='中度';
		}else if(200<=num&&num<300){
			idx=4;
			note='重度';
		}else if(num>300){
			idx=5;
			note='严重';
		}
		return {idx:idx,note:note}
	}
/**
 * //折线marker点颜色
 * @param {Number} num
 */
function get_line_markercolor(num){
	if(num>=0 && num<=50){
		return '#20c700';//绿色
	}else if(num<=100){
		return '#eedd4f';//黄色
	}else if(num<=150){
		return '#ff9d02';//橙色
	}else{
		return '#f63902';//红色
	}
}

/**
 * 获取指定月份的24小时时间段空气质量数据并刷新图表
 * 数据要求按时间线排序，格式见JSON_ONETIMEAIR.json
 * @param {String} url
 * @param {String} id
 * @param {String} month
 */
function make_wrchat_line(url,id,month,zb,min){
	var hisdata;
	var indexof = DataCaches['aqihours']['month'].indexOf(month);
	if(indexof<0 || !DataCachesEnable){
		//从接口获取数据
		//data?act=aqihours_new&areacode=2000&month=2016-05
		get_wrchat_data(url+'/data?act=aqihours_new&areacode=2000&month='+month,function(obj){
		//get_wrchat_data(url+'/data?act=aqihours&areacode=2000&month='+month,function(obj){
			hisdata = obj.Data;
			DataCaches['aqihours']['month'].push(month);//加入缓存
			DataCaches['aqihours']['data'].push(hisdata);
			_aqihours_dofun(hisdata,id,month,zb,min);
		});
	}else{
		hisdata = DataCaches['aqihours']['data'][indexof];
		_aqihours_dofun(hisdata,id,month,zb,min);
	}
}
function _aqihours_dofun(hisdata,id,month,zb,minz){
	var times=[];
	var alldata={};
	alldata['aqi'] = 0;
	alldata['pm25'] = 0;
	alldata['pm10'] = 0;
	alldata['so2'] = 0;
	alldata['no2'] = 0;
	alldata['co'] = 0;
	alldata['o3'] = 0;
	alldata['_aqi'] = [];
	alldata['_pm25'] = [];
	alldata['_pm10'] = [];
	alldata['_so2'] = [];
	alldata['_no2'] = [];
	alldata['_co'] = [];
	alldata['_o3'] = [];
	$.each(hisdata, function(i,e) {
		times.push(('0'+e.date+':00').substr(-5));
		alldata['aqi'] += parseFloat( e.aqi );
		alldata['_aqi'].push(parseFloat( e.aqi ));
		alldata['pm25'] += parseFloat( e.pm25 );
		alldata['_pm25'].push(parseFloat( e.pm25 ));
		alldata['pm10'] += parseFloat( e.pm10 );
		alldata['_pm10'].push(parseFloat( e.pm10 ));
		alldata['so2'] += parseFloat( e.so2 );
		alldata['_so2'].push(parseFloat( e.so2 ));
		alldata['no2'] += parseFloat( e.no2 );
		alldata['_no2'].push(parseFloat( e.no2 ));
		alldata['co'] += parseFloat( e.co );
		alldata['_co'].push(parseFloat( e.co ));
		alldata['o3'] += parseFloat( e.o3 );
		alldata['_o3'].push(parseFloat( e.o3 ));
	});
	var isChange = false;
	isChange = !zb ? true : false;
	zb = !zb ? 'aqi' : zb;
	//是否默认显示
	var aqiv = zb == 'aqi' ? true : false
	,pm25v = zb == 'pm25' ? true : false
	,pm10v = zb == 'pm10' ? true : false
	,so2v = zb == 'so2' ? true : false
	,no2v = zb == 'no2' ? true : false
	,cov = zb == 'co' ? true : false
	,o3v = zb == 'o3' ? true : false;
	
	//平均值
	var avgAqi=alldata['aqi']/24,
	avgPm25=alldata['pm25']/24,
	avgPm10=alldata['pm10']/24,
	avgSo2=alldata['so2']/24,
	avgNo2=alldata['no2']/24,
	avgCo=alldata['co']/24,
	avgO3=alldata['o3']/24,
	sum=0;
	//var avgAqi=0,avgPm25=0,avgPm10=0,avgSo2=0,avgNo2=0,avgCo=0,avgO3=0,sum=0;
	//最小值
	var minAqi=0,minPm25=0,minPm10=0,minSo2=0,minNo2=0,minCo=0,minO3=0;
	minAqi = Math.min.apply(null,alldata._aqi);
	minPm25 = Math.min.apply(null,alldata._pm25);
	minPm10 = Math.min.apply(null,alldata._pm10);
	minSo2 = Math.min.apply(null,alldata._so2);
	minNo2 = Math.min.apply(null,alldata._no2);
	minCo = Math.min.apply(null,alldata._co);
	minO3 = Math.min.apply(null,alldata._o3);
//	minAqi = Math.min.apply(null,hisdata.aqi);
//	minPm25 = Math.min.apply(null,hisdata.pm25);
//	minPm10 = Math.min.apply(null,hisdata.pm10);
//	minSo2 = Math.min.apply(null,hisdata.so2);
//	minNo2 = Math.min.apply(null,hisdata.no2);
//	minCo = Math.min.apply(null,hisdata.co);
//	minO3 = Math.min.apply(null,hisdata.o3);
	
	if(alldata['_'+zb].length<1){
		if(alldata._aqi.length<1){
			zb = 'pm25';
			aqiv = false;
			pm25v = true;
			if(alldata._pm25.length<1){
				zb = 'pm10';
				pm25v = false;
				pm10v = true;
				if(alldata._pm10.length<1){
					zb = 'so2';
					pm10v = false;
					so2v = true;
					if(alldata._so2.length<1){
						zb = 'no2';
						so2v = false;
						no2v = true;
						if(alldata._no2.length<1){
							zb = 'co';
							no2v = false;
							cov = true;
							if(alldata._co.length<1){
								zb = 'o3';
								cov = false;
								o3v = true;
								if(alldata._o3.length<1){
									zb = 'aqi';
									o3v = false;
									aqiv = true;
								}
							}
						}
					}
				}
			}
		}
	}
	
	if(aqiv){
		minz = minAqi;
	}else if(pm25v){
		minz = minPm25;
	}else if(pm10v){
		minz = minPm10;
	}else if(no2v){
		minz = minNo2;
	}else if(so2v){
		minz = minSo2;
	}else if(cov){
		minz = minCo;
	}else if(o3v){
		minz = minO3;
	}
	//组成x轴坐标，series数组
	//var times = hisdata.date,aqi=hisdata.aqi,co=hisdata.co,no2=hisdata.no2,o3=hisdata.o3,pm10=hisdata.pm10,pm25=hisdata.pm25,so2=hisdata.so2,ss=[];
	aqi=alldata._aqi,
	co=alldata._co,
	no2=alldata._no2,
	o3=alldata._o3,
	pm10=alldata._pm10,
	pm25=alldata._pm25,
	so2=alldata._so2,
	ss=[];
//	$.each(hisdata, function(i,e) {
//		times.push(('0'+e.date+':00').substr(-5));
//
//		if(i=='aqi'){
//			$.each(e, function(j,f) {
////				avgAqi+=parseFloat(f);
//				aqi[j]=parseFloat(f);
//			});
//		}
//		if(i=='pm25'){
//			$.each(e, function(j,f) {
////				avgPm25+=parseFloat(f);
//				pm25[j]=parseFloat(f);
//			});
//		}
//		if(i=='pm10'){
//			$.each(e, function(j,f) {
////				avgPm10+=parseFloat(f);
//				pm10[j]=parseFloat(f);
//			});
//		}
//		if(i=='so2'){
//			$.each(e, function(j,f) {
////				avgSo2+=parseFloat(f);
//				so2[j]=parseFloat(f);
//			});
//		}
//		if(i=='no2'){
//			$.each(e, function(j,f) {
////				avgNo2+=parseFloat(f);
//				no2[j]=parseFloat(f);
//			});
//		}
//		if(i=='co'){
//			$.each(e, function(j,f) {
////				avgCo+=parseFloat(f);
//				co[j]=parseFloat(f);
//			});
//		}
//		if(i=='o3'){
//			$.each(e, function(j,f) {
////				avgO3+=parseFloat(f);
//				o3[j]=parseFloat(f);
//			});
//		}
//	});
	
//	var sum = 24;
//	avgAqi=avgAqi/sum;
//	avgPm25=avgPm25/sum;
//	avgPm10=avgPm10/sum;
//	avgSo2=avgSo2/sum;
//	avgNo2=avgNo2/sum;
//	avgCo=avgCo/sum;
//	avgO3=avgO3/sum;
	$('.zhe .color-aqi').attr('avg',avgAqi);
	$('.zhe .color-pm25').attr('avg',avgPm25);
	$('.zhe .color-pm10').attr('avg',avgPm10);
	$('.zhe .color-so2').attr('avg',avgSo2);
	$('.zhe .color-no2').attr('avg',avgNo2);
	$('.zhe .color-co').attr('avg',avgCo);
	$('.zhe .color-o3').attr('avg',avgO3);
	
	$('.zhe .color-aqi').attr('min',minAqi);
	$('.zhe .color-pm25').attr('min',minPm25);
	$('.zhe .color-pm10').attr('min',minPm10);
	$('.zhe .color-so2').attr('min',minSo2);
	$('.zhe .color-no2').attr('min',minNo2);
	$('.zhe .color-co').attr('min',minCo);
	$('.zhe .color-o3').attr('min',minO3);
	
	var avgShow;
	avgShow = zb == 'aqi' ? avgAqi : ( zb == 'pm25' ? avgPm25 : ( zb == 'pm10' ? avgPm10 : ( zb == 'so2' ? avgSo2 : ( zb == 'no2' ? avgNo2 : ( zb == 'co' ? avgCo : ( zb == 'o3' ? avgO3 : avgAqi ) ) ) ) ) );
	
	var tmp=[],icon=[],min=getMin(alldata['_'+zb]);
	alldata['_'+zb].forEach(function(e,i){
		if(i==6){
			icon.push({y:minz-minz*0.05,marker:{width:11,height:11,symbol:getSymImgByNum(i)}});
		}else if(i==18){
			icon.push({y:minz-minz*0.05,marker:{width:11,height:11,symbol:getSymImgByNum(i)}});
		}else{
			icon.push({y:null});
		}
	});
	
	$.each(aqi, function(i,e) {
		tmp.push({y:e,color:num2color(e)});
		// tmp.push({y:e,marker:{fillColor:get_line_markercolor(e),lineColor:'#FE9A01',lineWidth:1,width:11,height:11,symbol:getSymImgByNum(times[i])}});//,lineColor:'#6f88c8'
	});
	aqi=tmp;tmp=[];
	$.each(pm25, function(i,e) {
		tmp.push({y:e,color:num2color(e)});
		// tmp.push({y:e,marker:{fillColor:'#00E3D8',lineWidth:1,width:11,height:11,symbol:getSymImgByNum(times[i])}});//,lineColor:'#00E3D8'
	});
	pm25=tmp;tmp=[];
	$.each(pm10, function(i,e) {
		tmp.push({y:e,color:num2color(e)});
		// tmp.push({y:e,marker:{fillColor:'#23ae39',lineWidth:1,width:11,height:11,symbol:getSymImgByNum(times[i])}});//,lineColor:'#23ae39'
	});
	pm10=tmp;tmp=[];
	$.each(so2, function(i,e) {
		tmp.push({y:e,color:num2color(e)});
		// tmp.push({y:e,marker:{fillColor:'#e4b503',lineWidth:1,width:11,height:11,symbol:getSymImgByNum(times[i])}});//,lineColor:'#e4b503'
	});
	so2=tmp;tmp=[];
	$.each(no2, function(i,e) {
		tmp.push({y:e,color:num2color(e)});
		// tmp.push({y:e,marker:{fillColor:'#688ff4',lineWidth:1,width:11,height:11,symbol:getSymImgByNum(times[i])}});//,lineColor:'#688ff4'
	});
	no2=tmp;tmp=[];
	$.each(co, function(i,e) {
		tmp.push({y:e,color:num2color(e)});
		// tmp.push({y:e,marker:{fillColor:'#e16f6e',lineWidth:1,width:11,height:11,symbol:getSymImgByNum(times[i])}});//,lineColor:'#e16f6e'
	});
	co=tmp;tmp=[];
	$.each(o3, function(i,e) {
		tmp.push({y:e,color:num2color(e)});
		// tmp.push({y:e,marker:{fillColor:'#01b3d9',lineWidth:1,width:11,height:11,symbol:getSymImgByNum(times[i])}});//,lineColor:'#01b3d9'
	});
	o3=tmp;tmp=[];
	ss=[{name:'AQI',data:aqi,visible:aqiv}
	,{name:'PM2.5',data:pm25,visible:pm25v}
	,{name:'PM10',data:pm10,visible:pm10v}
	,{name:'SO2',data:so2,visible:so2v}
	,{name:'NO2',data:no2,visible:no2v}
	,{name:'CO',data:co,visible:cov}
	,{name:'O3',data:o3,visible:o3v}
	,{name:'min',data:icon,visible:true}];
	// time.map(function(e,i){
	// 	if(i>=6&&i<=18) return e+'☀'
	// 	return e
	// });
	$('#'+id).highcharts({
        title: {
           text: null
        },
        colors:['#FE9A01','#00E3D8','#23ae39','#e4b503','#688ff4','#e16f6e','#01b3d9'],
        yAxis: {
            title: {
                text: null
            },
            tickWidth:1,
            tickLength:5,
//	            tickInterval:10,
			min:minz?minz-minz*0.05:null,
			startOnTick:false,
            endOnTick:false,
            lineWidth:1,
            minPadding:0.05,
            gridLineWidth:0,
            plotLines:[{
            	color: avgColor[zb],
            	dashStyle:'ShortDash',
            	width: 1,
            	value: avgShow,
            	id:'PlotLine-'+zb
            }]
        },
        credits:{
        	enabled: false
        },
        tooltip:{
        	crosshairs: true//[true,true]
        	,shared: true
        },
        legend: {
        	enabled:false
        },
        xAxis: {
            categories: times
            ,tickLength:0
        	,labels:{
        		rotation:270
            	,step:1
        	}
        	,id:'xAxitsLine-times'
			,plotBands: [{
                color: 'rgba(0, 94, 205,0.025)',
                from: -1,
                to: 6
            },{
                color: 'RGBA(252, 255, 197, 0.25)',
                from: 6,
                to: 18
            },{
                color: 'rgba(0, 94, 205,0.025)',
                from: 18,
                to: 24
            }]
        },
		series: ss
		,chart:{
			events:{
				load:function(){
					if(isChange) $('.zhe').find('.color-'+zb).addClass('active');
				}
			}
		}
    },function(charts){
    	tysjd_chart = charts;
    });
}

function getMin(arr){
	var i=0,l=arr.length;
	var min=500;
	for(;i<l;i++){
		if(min>arr[i]){
			min=arr[i];
		}
	}
	return min
}
/**
 * 根据时间点获取日月图标
 * @param {String} num 时间点:example//08:00 20:00
 */
function getSymImgByNum(num){
	var t = parseInt(num);
	if(t>=6 && t<18){
		//sun
		return 'url(assets/img/sun.png)';
	}else{
		//moon
		return 'url(assets/img/moon.png)';
	}
}

/**
 * 补零函数 向左补零 取两位
 * @param {String} str
 */
function appendZeroleft(str){
	return ('0'+str).substr(-2,2);
}

function num2color(num){
	var num=parseInt(num);
	var color='#23C700';
	if(num<50){
		color='#23C700';
	}else if(50<num&&num<=100){
		color='#ECD814';
	}else if(100<num&&num<=150){
		color='#FF9D01';
	}else if(150<num&&num<=200){
		color='#F83702';
	}else if(200<num&&num<=300){
		color='#CD162E';
	}else if(num>300){
		color='#8E0C30';
	}
	return color
}

